#!/usr/bin/env python3
"""
简单的服务器启动测试脚本
"""

import sys
import os
import time
import requests
import subprocess
import threading

def test_import():
    """测试导入"""
    try:
        print("测试导入模块...")
        from backend.main import app
        print("✅ 导入成功")
        return True
    except Exception as e:
        print(f"❌ 导入失败: {e}")
        return False

def start_server():
    """启动服务器"""
    try:
        print("启动服务器...")
        import uvicorn
        from backend.main import app
        
        # 在新线程中启动服务器
        def run_server():
            uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
        
        server_thread = threading.Thread(target=run_server, daemon=True)
        server_thread.start()
        
        # 等待服务器启动
        print("等待服务器启动...")
        time.sleep(3)
        
        return True
    except Exception as e:
        print(f"❌ 启动服务器失败: {e}")
        return False

def test_health():
    """测试健康检查"""
    try:
        print("测试健康检查...")
        response = requests.get("http://localhost:8000/health", timeout=5)
        if response.status_code == 200:
            print("✅ 健康检查通过")
            print(f"响应: {response.json()}")
            return True
        else:
            print(f"❌ 健康检查失败: {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ 健康检查异常: {e}")
        return False

def test_basic_apis():
    """测试基础API"""
    base_url = "http://localhost:8000"
    
    # 测试获取题目
    try:
        print("测试获取题目API...")
        response = requests.get(f"{base_url}/api/questions", timeout=5)
        print(f"GET /api/questions: {response.status_code}")
        if response.status_code == 200:
            questions = response.json()
            print(f"✅ 获取到 {len(questions)} 道题目")
        else:
            print(f"❌ 获取题目失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 获取题目异常: {e}")
    
    # 测试管理员接口
    try:
        print("测试管理员API...")
        headers = {"Authorization": "Bearer admin_secret_token_2024"}
        response = requests.get(f"{base_url}/admin/question-banks", headers=headers, timeout=5)
        print(f"GET /admin/question-banks: {response.status_code}")
        if response.status_code == 200:
            banks = response.json()
            print(f"✅ 获取到 {len(banks)} 个题库")
        else:
            print(f"❌ 获取题库失败: {response.status_code}")
    except Exception as e:
        print(f"❌ 获取题库异常: {e}")

def main():
    print("🚀 开始服务器测试...")
    print("="*50)
    
    # 1. 测试导入
    if not test_import():
        sys.exit(1)
    
    # 2. 启动服务器
    if not start_server():
        sys.exit(1)
    
    # 3. 测试健康检查
    if not test_health():
        print("尝试等待更长时间...")
        time.sleep(5)
        if not test_health():
            sys.exit(1)
    
    # 4. 测试基础API
    test_basic_apis()
    
    print("\n✅ 服务器测试完成！")
    print("服务器正在运行在: http://localhost:8000")
    print("按 Ctrl+C 停止服务器")
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")

if __name__ == "__main__":
    main()
